package com.repair.filter;



import com.repair.entity.JwtUtil;
import com.repair.entity.PassUrlProperties;
import com.repair.exception.RepairException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;

//@Component
public class UserLoginFilter implements GlobalFilter {
    @Autowired
    private PassUrlProperties passUrlProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getPath().toString();
//        if (url.endsWith(".api")){
//            //访问的管理员接口，进行放行
//           return chain.filter(exchange);
//        }
        System.out.println("=============进行用户登录认证==========");
        //判断访问的是否是公共的放行接口
        List<String> baseUrls = passUrlProperties.getBaseUrls();
        if (baseUrls!=null && baseUrls.size()>0){
            for (String baseUrl : baseUrls) {
                if (antPathMatcher.match(baseUrl,url)) {
                    //是放行的接口
                    return chain.filter(exchange);
                }
            }
        }
        //访问没有放行的接口，进行登录认证
        List<String> values = exchange.getRequest().getHeaders().get("token");
        String token = null;
        if (values!=null && values.size()>0){
            token=values.get(0);
        }
        if (token==null) throw new RepairException(401,"未登录");
        //验证token
        try {
            JwtUtil.parseToken(token);
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RepairException(401,"未登录");
        }

    }

    public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("orderUser","13312341234");
        String token = JwtUtil.createToken(map, 30);
        System.out.println(token);
    }
}
